/**
 * 支持自定义请求头的 WebSocket 客户端
 * 使用 SockJS 或其他方式实现
 */

// 注意：原生 WebSocket 不支持自定义请求头
// 这里提供几种替代方案

/**
 * 方案1：使用 SockJS（需要引入 SockJS 库）
 */
class SockJSWebSocketClient {
    constructor(url, token = null) {
        this.baseUrl = url;
        this.token = token;
        this.sock = null;
        this.isConnected = false;
        this.messageHandlers = new Map();
        this.connectionHandlers = [];
    }

    connect(onOpen, onClose, onError) {
        try {
            // 创建 SockJS 连接，支持自定义请求头
            this.sock = new SockJS(this.baseUrl, null, {
                transports: ['websocket', 'xhr-streaming', 'xhr-polling'],
                headers: {
                    'token': this.token
                }
            });

            this.sock.onopen = (event) => {
                this.isConnected = true;
                console.log('SockJS 连接已建立');
                if (onOpen) onOpen(event);
            };

            this.sock.onmessage = (event) => {
                console.log('收到消息:', event.data);
                this.handleMessage(event.data);
            };

            this.sock.onclose = (event) => {
                this.isConnected = false;
                console.log('SockJS 连接已关闭');
                if (onClose) onClose(event);
            };

            this.sock.onerror = (error) => {
                console.error('SockJS 错误:', error);
                if (onError) onError(error);
            };

        } catch (error) {
            console.error('连接失败:', error);
            if (onError) onError(error);
        }
    }

    sendMessage(action, data) {
        if (!this.isConnected || !this.sock) {
            console.error('SockJS 未连接');
            return false;
        }

        const message = {
            action: action,
            data: data
        };

        try {
            this.sock.send(JSON.stringify(message));
            console.log('发送消息:', message);
            return true;
        } catch (error) {
            console.error('发送消息失败:', error);
            return false;
        }
    }

    disconnect() {
        if (this.sock) {
            this.sock.close();
            this.sock = null;
            this.isConnected = false;
        }
    }

    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            const handler = this.messageHandlers.get(message.action);
            if (handler) {
                handler(message.data);
            }
        } catch (error) {
            console.log('收到文本消息:', data);
            const handler = this.messageHandlers.get('text');
            if (handler) {
                handler(data);
            }
        }
    }

    onMessage(action, handler) {
        this.messageHandlers.set(action, handler);
    }
}

/**
 * 方案2：使用 HTTP 升级到 WebSocket（需要后端支持）
 */
class HTTPUpgradeWebSocketClient {
    constructor(url, token = null) {
        this.baseUrl = url;
        this.token = token;
        this.ws = null;
        this.isConnected = false;
    }

    connect(onOpen, onClose, onError) {
        try {
            // 创建 XMLHttpRequest 进行 HTTP 升级
            const xhr = new XMLHttpRequest();
            xhr.open('GET', this.baseUrl, true);
            xhr.setRequestHeader('Upgrade', 'websocket');
            xhr.setRequestHeader('Connection', 'Upgrade');
            xhr.setRequestHeader('Sec-WebSocket-Key', this.generateWebSocketKey());
            xhr.setRequestHeader('Sec-WebSocket-Version', '13');
            xhr.setRequestHeader('token', this.token);

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 101) {
                        // 升级成功，创建 WebSocket
                        this.ws = new WebSocket(this.baseUrl);
                        this.setupWebSocketHandlers(onOpen, onClose, onError);
                    } else {
                        console.error('HTTP 升级失败:', xhr.status);
                        if (onError) onError(new Error('HTTP upgrade failed'));
                    }
                }
            };

            xhr.send();

        } catch (error) {
            console.error('连接失败:', error);
            if (onError) onError(error);
        }
    }

    generateWebSocketKey() {
        // 生成随机的 WebSocket Key
        const array = new Uint8Array(16);
        crypto.getRandomValues(array);
        return btoa(String.fromCharCode.apply(null, array));
    }

    setupWebSocketHandlers(onOpen, onClose, onError) {
        this.ws.onopen = (event) => {
            this.isConnected = true;
            console.log('WebSocket 连接已建立');
            if (onOpen) onOpen(event);
        };

        this.ws.onmessage = (event) => {
            console.log('收到消息:', event.data);
        };

        this.ws.onclose = (event) => {
            this.isConnected = false;
            console.log('WebSocket 连接已关闭');
            if (onClose) onClose(event);
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
            if (onError) onError(error);
        };
    }

    sendMessage(action, data) {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket 未连接');
            return false;
        }

        const message = {
            action: action,
            data: data
        };

        try {
            this.ws.send(JSON.stringify(message));
            return true;
        } catch (error) {
            console.error('发送消息失败:', error);
            return false;
        }
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
            this.isConnected = false;
        }
    }
}

/**
 * 方案3：使用 fetch API 进行 WebSocket 握手（现代浏览器）
 */
class FetchWebSocketClient {
    constructor(url, token = null) {
        this.baseUrl = url;
        this.token = token;
        this.ws = null;
        this.isConnected = false;
    }

    async connect(onOpen, onClose, onError) {
        try {
            // 使用 fetch 进行握手
            const response = await fetch(this.baseUrl, {
                method: 'GET',
                headers: {
                    'Upgrade': 'websocket',
                    'Connection': 'Upgrade',
                    'Sec-WebSocket-Key': this.generateWebSocketKey(),
                    'Sec-WebSocket-Version': '13',
                    'token': this.token
                }
            });

            if (response.status === 101) {
                // 握手成功，创建 WebSocket
                this.ws = new WebSocket(this.baseUrl);
                this.setupWebSocketHandlers(onOpen, onClose, onError);
            } else {
                throw new Error('WebSocket 握手失败');
            }

        } catch (error) {
            console.error('连接失败:', error);
            if (onError) onError(error);
        }
    }

    generateWebSocketKey() {
        const array = new Uint8Array(16);
        crypto.getRandomValues(array);
        return btoa(String.fromCharCode.apply(null, array));
    }

    setupWebSocketHandlers(onOpen, onClose, onError) {
        this.ws.onopen = (event) => {
            this.isConnected = true;
            console.log('WebSocket 连接已建立');
            if (onOpen) onOpen(event);
        };

        this.ws.onmessage = (event) => {
            console.log('收到消息:', event.data);
        };

        this.ws.onclose = (event) => {
            this.isConnected = false;
            console.log('WebSocket 连接已关闭');
            if (onClose) onClose(event);
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket 错误:', error);
            if (onError) onError(error);
        };
    }

    sendMessage(action, data) {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket 未连接');
            return false;
        }

        const message = {
            action: action,
            data: data
        };

        try {
            this.ws.send(JSON.stringify(message));
            return true;
        } catch (error) {
            console.error('发送消息失败:', error);
            return false;
        }
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
            this.isConnected = false;
        }
    }
}

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { 
        SockJSWebSocketClient, 
        HTTPUpgradeWebSocketClient, 
        FetchWebSocketClient 
    };
} 